package com.tree.thread.pubsub;

import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @ClassName com.tree.thread.pubsub
 * Description: <类功能描述>. <br>
 * <p>
 * 使用信号量实现生产者消费者
 * </p>
 * @Author tree
 * @Date 2019-11-02 15:53
 * @Version 1.0
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        SemaphoreStorage storage = new SemaphoreStorage();
        for(int i = 0; i< 3; i++){
            new Thread(new Producer(storage),"生产者-"+i).start();
            new Thread(new Consumer(storage),"消费者-"+i).start();
        }
    }

    static class SemaphoreStorage implements IStorage{
        private static int FULL = 10;
        private int count = 0;
        /**
         * 最大容量
         */
        Semaphore notFull = new Semaphore(FULL);

        /**
         *  将线程挂起，等待其他来触发
         */
        final Semaphore notEmpty = new Semaphore(0);
        /**
         * // 互斥锁
         */
        Semaphore mutex = new Semaphore(1);


        @Override
        public void produce() {
            try {
                String threadName = Thread.currentThread().getName();
                notFull.acquire();
//                mutex.acquire();
                count++;
                System.out.println("生产者【" + threadName+ "】生产一个产品，现库存" + count);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
//                mutex.release();
                notEmpty.release();
            }

        }

        @Override
        public void consume() {
            try {
                String threadName = Thread.currentThread().getName();
                notEmpty.acquire();
//                mutex.acquire();
                count--;
                System.out.println("消费者【" + threadName+ "】消费一个产品，现库存" + count);


            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
//                mutex.release();
                notFull.release();
            }
        }
    }
}
